package com.ly.mpayment.persist.service.uporder;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.provincialinformation.IProvincialInformationService;
import com.ly.mpayment.persist.service.upshoppro.IUpShopProService;
import com.ly.mpayment.rest.system.BigDecimalUtil;
import com.ly.mpayment.rest.up.OrderHandler;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.mortbay.log.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.AbstractService;
import com.ly.mpayment.persist.service.debituplog.IDebitUpLogService;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.persist.service.yidong.IMobileOrdersService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.util.CollectionUtils;

@Service
public class UporderServiceImpl extends AbstractService<UpOrder, Serializable> implements IUporderService {

	Logger logger = Logger.getLogger(UporderServiceImpl.class);

	@Autowired
	IDownRechargeFlowService flowService;
	@Autowired
	IUpShopInfoService upShopInfoService;

	@Autowired
	IDebitUpLogService logService;

	@Autowired
	ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	private IUpShopProService upShopProService;

	@Autowired
	private IProvincialInformationService provincialInformationService;

	@Autowired
	IMobileOrdersService ordersService;

	@Override
	public UpOrder saveOrder(UpOrder order) {
		if (order != null) {
			DownRechargeFlow flow = this.flowService.findById(order.getDownRechargeFlow().getDownorderuuid());
			//下游订单状态为充值中才创建上游订单
			if (flow.getStatus() == Config.status[0]) {
				UpOrder orderCheck = findByDownFlowRechare(flow.getDownorderuuid());
				if (orderCheck == null) {
					order = this.saveOrUpdate(order);
				} else {
					logger.info("orderCheck_订单已存在:" + orderCheck.getUpphonenum());
					return null;
				}
			}else{
				logger.info("order下游订单状态错误:" + flow.getStatus());
				return null;
			}
			if(order == null || order.getUporderuuid() == null){
				logger.info("上游订单未保存:" + order);
				return null;
			}
			return order;
		}else{
			logger.info("orderCheck_异常:" + order);
		}
		return null;
	}

	@Override
	public UpOrder updateOrder(UpOrder order, UpShopInfo shop) {
		if (order != null && shop != null) {
			upShopInfoService.updateUpshopinfo(shop);
			this.updateEntity(order);
			return order;
		}
		return null;
		// return updateOrderBalance(order, null, shop);
	}

	@Override
	public UpOrder findById(String orderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder where u.status = 1 and u.uporderuuid = ? ",
				orderuuid);
	}

	@Override
	public UpOrder findByShopId(String orderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.upShopPro where u.uporderuuid = ? ",
				orderuuid);
	}

	@Override
	public UpOrder findByCallId(String orderId) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow left join fetch u.upShopPro where" +
						" u.uporderuuid = ? and  ( u.status = 1 or u.status = 10 or u.status = 11 or u.status = 2  or u.status = 5  )",
				orderId);
	}

	@Override
	public DownRechargeFlow updateOrderBalance(UpOrder order, DownRechargeFlow flow, UpShopInfo shop) throws Exception {
		if (order != null && flow != null) {
			order = findByCallId(order.getUporderuuid());
			// 更新自动订单匹配 状态 为失败
			// 订单成功后 需要减去上游渠道商账户余额
			UpShopInfo shopInfo = upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
			if (shopInfo != null && (order.getStatus() == Config.status[0] || order.getStatus() == Config.status[10] || order.getStatus() == Config.status[11])) {// 改变状态前的订单是充值中
				shopInfo.setUpshopbalance(shopInfo.getUpshopbalance().subtract(order.getDiscountAmount()));
				this.upShopInfoService.updateUpshopinfo(shopInfo);
				logger.info("扣款上游订单:" + order.getDiscountAmount() + "," + order.getUpphonenum());
				DebitUpLog log = new DebitUpLog();
				log.setDebitAmount(order.getDiscountAmount());
				log.setDebitTime(DateUtils.getNowDate());
				log.setDebitStatus(Config.debitSuccess);
				log.setUpShopInfo(shopInfo);
				log.setUpOrder(order);
				log.setStatus(Config.publicStatus[1]);
				log.setBalance(shopInfo.getUpshopbalance());
				logService.saveDebitLog(log);
			} else {
				if(shopInfo == null){
					throw new Exception("供货渠道信息为空:"+order.getUpphonenum());
				}
				logger.info("updateOrderBalance_shopInfo_is_null:"+order.getUpphonenum());
			}
			Date end = DateUtils.getNowDate();
			// 回调时需要根据结果判断成功或者失败 ，当前默认成功
			order.setStatusremark(Config.orderSuccess);
			order.setUpendtime(end);
			order.setUpendtimesec(((Long) (end.getTime() - order.getCreatetime().getTime())).intValue());
			order.setStatus(Config.status[1]);
			order.setCallBack(Config.callStatus[1]);
			order.setSendStatus(Config.sendStatus[0]);
			this.updateEntity(order);
			flow = this.flowService.findById(flow.getDownorderuuid());
			if (flow != null) {
				// 更细分销商订单状态
				flow.setStatus(Config.status[1]);
				flow.setDownendtimesec(((Long) (end.getTime() - flow.getCreatetime().getTime())).intValue());
				flow.setDownendtime(end);
				//flow.setStatusremark(Config.orderSuccess);
				flow.setRemark(order.getRemark());
				// flow.setCallStatus(Config.callStatus[1]);
				this.flowService.updateDownrechargeflow(flow);
				logger.info("修改订单状态:" + flow.getStatus() + "," + flow.getDowonphonenum());
				// 检查上游订单状态是否正确
				return flow;
			}
		} else if (order != null && shop != null) {
			upShopInfoService.updateUpshopinfo(shop);
			this.updateEntity(order);
		} else if (order != null) {
			this.updateEntity(order);
		}
		return null;
	}

	@Override
	public UpOrder findByDownFlowId(String downId) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.upShopPro where (u.status = 1 or u.status = 10 or u.status = 11) and u.downRechargeFlow.downorderuuid = ? ",
				downId);
	}

	/**
	 * 添加订单前检查是否存在
	 */
	@Override
	public UpOrder findByDownFlowIdSql(String downId) {
		// (u.status = 1 or u.status = 2) and
		return this.findUnique("select u from UpOrder u  where  u.downRechargeFlow.downorderuuid = ? ", downId);
	}


	/**
	 * 不能修改
	 * @param downorderuuid
	 * @return
	 */
	@Override
	public UpOrder findByDownFlowRechare(String downorderuuid) {
		return this.findUnique("select u from UpOrder u  where u.status = 1 and u.downRechargeFlow.downorderuuid = ? ", downorderuuid);
	}

	@Override
	public List<UpOrder> findByDownOrderId(String downorderuuid) {
		String hql = "select u from UpOrder u left join fetch u.upShopPro where u.downRechargeFlow.downorderuuid = ? ";
		return this.find(hql,downorderuuid);
	}

	/**
	 * 添加订单前检查是否存在
	 */
	@Override
	public UpOrder findByDownFlowIdSqlMaintenances(String downId) {
		return this.findUnique(
				"select u from UpOrder u  where  u.status = 9  and u.downRechargeFlow.downorderuuid = ? ", downId);
	}

	@Override
	public Page<UpOrder> findPageOrder(Map<String, Object> parameters, int start, int pageSize,boolean oderBy) {
		Page<UpOrder> orderPage = this.findPageByNamed(getPageSql(parameters,oderBy), parameters, start, pageSize);
		return orderPage;
	}
	//updateOrderStatus(orderPage.getResult());
	public int updateOrderStatus(List<UpOrder> list){
		if(CollectionUtils.isEmpty(list)){
			return 0;
		}
		String upprouuids = "";
		for(int i = 0 ; i < list.size() ; i++){
			upprouuids += "'"+list.get(i).getUporderuuid().toString()+"',";
		}
		if(!upprouuids.equals("")){
			upprouuids = upprouuids.substring(0,upprouuids.lastIndexOf(","));
		}
		if(!upprouuids.equals("")){
			String updateSql = " update uporder set status = 1 where uporderuuid in ("+upprouuids+") ";
			Session session = this.getSessionFactory().openSession();
			Transaction transaction = session.beginTransaction();
			transaction.begin();
			int num = session.createSQLQuery(updateSql).executeUpdate();
			if(num != list.size()){
				transaction.rollback();
				return 0;
			}
			transaction.commit();
			session.flush();
			session.close();
			return num;
		}
		return 0;
	}

	private String getPageSql(Map<String, Object> parameters,boolean oderBy) {
		String hql = "select u from UpOrder u left join fetch u.userOrder left join fetch u.information pi  left join fetch u.upShopPro p "
				+ " left join fetch p.businessType bt left join fetch u.downRechargeFlow where u.status <> 0 "
				+ " #[and u.status = :status]#  #[and bt.busuuid = :busuuid]#  #[and p.productCode = :productCode]#  #[and u.province = :province]#  "
				+ " #[and u.uporderuuid = :uporderuuid]# #[and u.upOrderId = :upOrderId]#  #[and u.userOrder.useruuid = :useruuid]#  #[and u.upphonenum = :phoneNum]# #[and u.callBack = :callBack]# "
				+ " #[and p.upfacevalue = :upfacevalue]#  #[and u.downShopName = :downShopName]# #[and u.operators = :operatoruid]# ";

		if (parameters.containsKey(":createtime")) {
			hql += " and u.createtime >= '".concat(parameters.get(":createtime").toString()).concat("'");
			parameters.remove(":createtime");
		}
		if (parameters.containsKey(":endtime")) {
			hql += " and u.createtime <= '".concat(parameters.get(":endtime").toString()).concat("'");
			parameters.remove(":endtime");
		}

		if (parameters.containsKey(":upOrderIds")) {
			String temps[] = parameters.get(":upOrderIds").toString().split(",");
			List<String> strs = new ArrayList<>();
			for(int i = 0 ; i < temps.length; i++){
				strs.add("'" + temps[i] + "'");
			}
			//上游单号
			//hql += " and u.upOrderId in ("+String.join(",", strs)+")";
			//平台方上游单号

			hql += " and u.uporderuuid in ("+String.join(",", strs)+")";
			parameters.remove(":upOrderIds");
		}

		//处理导入按上游订单查询数组
		hql += " order by u.createtime " +( oderBy == true ? "desc" : "");
		return hql;
	}

	@Override
	public List<UpOrder> findOrders(Integer pageSize, int start, int minutes) {
		Map<String, Object> parameters = MapUtil.getMap();
		parameters.put(":currentDate", DateUtils.subtractionMinutes(minutes, DateUtils.getNowDate()));
		return this.findPageByNamed(
				"select u from UpOrder u left join fetch u.userOrder where u.status = 1 and u.callBack = 0  and u.createtime <= :currentDate",
				parameters, start, pageSize).getResult();
	}

	@Override
	public UpOrder updateOrder(UpOrder order) {
		if (order != null) {
			this.updateEntity(order);
			// 更新自动订单匹配 状态
			return order;
		}
		return null;
	}

//	@Override
//	public UpOrder findByDownFlowIdFail(String downId) {
//		return this.findUnique(
//				"select u from UpOrder u left join fetch u.upShopPro where u.status = 4 and u.downRechargeFlow.downorderuuid = ? ",
//				downId);
//	}

//	@Override
//	public UpOrder findByDownFlowIdSuccess(String downId) {
//		return this.findUnique(
//				"select u from UpOrder u left join fetch u.upShopPro where u.status = 2 and u.downRechargeFlow.downorderuuid = ? ",
//				downId);
//	}

	@Override
	public List<UpOrder> orderCommitFailt(Integer pageSize, int start) {
		return this.findPageByNamed(
				"select u from UpOrder u left join fetch u.userOrder where   u.status = 1 and u.sendStatus = 1 order by u.createtime",
				MapUtil.getMap(), start, pageSize).getResult();
	}

	@Override
	public UpOrder findBySantiOrderId(String orderId) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.upOrderId = ? ",
				orderId);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String getUpCount(Map<String, Object> parameters, int start, int pageSize) {

		Page pa = new Page();
		pa.setStart(start);
		pa.setPageSize(pageSize);
		Page page = PaginationUtil.queryPaginationSQL("select * from (" + getSql(parameters) + ") temps ", pa,
				this.getSession());
		List lists = page.getResult();
		if (lists != null) {
			JSONArray array = JsonUtils.getJSONARRAY();
			// [402880ec60e5bd8d0160e5d0f2210001, 111, 全国半年包, 中国电信, 165.0000000,
			// null, null, 165.0000000, 15, 0, 0, 0]
			for (int i = 0; i < lists.size(); i++) {
				JSONObject obj = JsonUtils.getJSONOBJCT();
				Object[] object = (Object[]) lists.get(i);
				obj.put("useruuid", object[0] == null ? "" : object[0].toString());
				obj.put("username", object[1] == null ? "" : object[1].toString());
				obj.put("busname", object[2].toString());
				obj.put("operatorname", object[3].toString());
				obj.put("sumamount", object[4] == null ? 0 : new BigDecimal(object[4].toString()).setScale(5));
				obj.put("success", object[5] == null ? 0 : new BigDecimal(object[5].toString()).setScale(5));
				obj.put("failt", object[6] == null ? 0 : new BigDecimal(object[6].toString()).setScale(5));
				obj.put("wait", object[7] == null ? 0 : new BigDecimal(object[7].toString()).setScale(5));
				obj.put("sumorder", object[8] == null ? 0 : object[8].toString());
				obj.put("successorder", object[9] == null ? 0 : object[9].toString());
				obj.put("failtorder", object[10] == null ? 0 : object[10].toString());
				obj.put("waitorder", object[11] == null ? 0 : object[11].toString());
				obj.put("provincename", object[12] == null ? 0 : object[12].toString());
				obj.put("profit", object[13] == null ? 0 : new BigDecimal(object[13].toString()).setScale(5));
				obj.put("successRate",
						object[9] == null ? 0
								: (Integer.valueOf(object[9].toString())
										/ (object[8] == null ? 0 : Integer.valueOf(object[8].toString()))));
				array.add(obj);
			}
			page.setResult(array);
			return JsonUtils.convertObjectToJson(page);
		}
		return JsonUtils.getJSONARRAY().toString();
	}

	private String getSql(Map<String, Object> parameters) {
		String su = "";
		if (parameters.containsKey("useruuid")) {
			su += " and su.useruuid ='" + parameters.get("useruuid").toString().concat("' ");
		}
		if (parameters.containsKey("busuuid")) {
			su += " and bs.busuuid ='" + parameters.get("busuuid").toString().concat("' ");
		}
		if (parameters.containsKey("provinceuuid")) {
			su += " and su.provinceuuid  ='" + parameters.get("provinceuuid").toString().concat("' ");
		}
		if (parameters.containsKey("facevalue")) {
			su += " and su.rechargeamount =" + parameters.get("facevalue").toString().concat(" ");
		}
		if (parameters.containsKey("starttime")) {
			su += " and DATE_FORMAT(su.createtime,'%Y-%m-%d') >='"
					+ parameters.get("starttime").toString().concat("' ");
		}
		if (parameters.containsKey("endtime")) {
			su += " and DATE_FORMAT(su.createtime,'%Y-%m-%d') <='" + parameters.get("endtime").toString().concat("' ");
		}
		String dfl = "";
		if (parameters.containsKey("useruuid")) {
			dfl += " and dfl.useruuid ='" + parameters.get("useruuid").toString().concat("' ");
		}
		if (parameters.containsKey("busuuid")) {
			dfl += " and bs.busuuid ='" + parameters.get("busuuid").toString().concat("' ");
		}
		if (parameters.containsKey("provinceuuid")) {
			dfl += " and dfl.provinceuuid  ='" + parameters.get("provinceuuid").toString().concat("' ");
		}
		if (parameters.containsKey("facevalue")) {
			dfl += " and dfl.rechargeamount =" + parameters.get("facevalue").toString().concat(" ");
		}
		if (parameters.containsKey("starttime")) {
			dfl += " and DATE_FORMAT(dfl.createtime,'%Y-%m-%d') >='"
					+ parameters.get("starttime").toString().concat("' ");
		}
		if (parameters.containsKey("endtime")) {
			dfl += " and DATE_FORMAT(dfl.createtime,'%Y-%m-%d') <='"
					+ parameters.get("endtime").toString().concat("' ");
		}
		String profit = "";
		if (parameters.containsKey("useruuid")) {
			profit += " and ups.useruuid ='" + parameters.get("useruuid").toString().concat("' ");
		}
		if (parameters.containsKey("busuuid")) {
			profit += " and bs.busuuid ='" + parameters.get("busuuid").toString().concat("' ");
		}
		if (parameters.containsKey("provinceuuid")) {
			profit += " and ups.provinceuuid  ='" + parameters.get("provinceuuid").toString().concat("' ");
		}
		if (parameters.containsKey("facevalue")) {
			profit += " and ups.rechargeamount =" + parameters.get("facevalue").toString().concat(" ");
		}
		if (parameters.containsKey("starttime")) {
			profit += " and DATE_FORMAT(ups.createtime,'%Y-%m-%d') >='"
					+ parameters.get("starttime").toString().concat("' ");
		}
		if (parameters.containsKey("endtime")) {
			profit += " and DATE_FORMAT(ups.createtime,'%Y-%m-%d') <='"
					+ parameters.get("endtime").toString().concat("' ");
		}

		String sql = "  select up.useruuid,u.username,bs.busname,op.operatorname,sum(up.discount_amount) as "
				+ " 'orderamount',(select sum(su.discount_amount) from uporder su,businesstype bs,upshopproduct ud where su.useruuid = up.useruuid "
				+ " and ud.busuuid = bs.busuuid and up.upprouuid = ud.upprouuid and su.status = 2 and up.provinceuuid = su.provinceuuid "
				+ su + ")  "
				+ " as 'success' ,(select sum(su.discount_amount) from uporder su,businesstype bs,upshopproduct ud where su.useruuid = up.useruuid "
				+ " and ud.busuuid = bs.busuuid and up.upprouuid = ud.upprouuid  and su.status = 3 and up.provinceuuid = su.provinceuuid "
				+ su + " )"
				+ " as 'failt',(select sum(su.discount_amount) from uporder su,businesstype bs,upshopproduct ud where su.useruuid = up.useruuid "
				+ " and ud.busuuid = bs.busuuid and up.upprouuid = ud.upprouuid and su.status = 1 and up.provinceuuid = su.provinceuuid "
				+ su + ") "
				+ " as 'wait',count(up.uporderuuid) as 'sumorder',(select count(dfl.operatoruid) from uporder dfl,businesstype bs,upshopproduct ud "
				+ " where dfl.useruuid = up.useruuid and ud.busuuid = bs.busuuid and dfl.upprouuid = ud.upprouuid and dfl.status = 2 and up.provinceuuid = dfl.provinceuuid "
				+ dfl + ") as 'successorder',"
				+ " (select count(dfl.operatoruid) from uporder dfl,businesstype bs,upshopproduct ud  where dfl.useruuid = up.useruuid and ud.busuuid = bs.busuuid"
				+ " and dfl.upprouuid = ud.upprouuid and ud.busuuid = bs.busuuid and dfl.upprouuid = ud.upprouuid and dfl.status = 3 and up.provinceuuid = dfl.provinceuuid "
				+ dfl + ") "
				+ " as 'failtorder',(select count(dfl.operatoruid) from uporder dfl,businesstype bs,upshopproduct ud where dfl.useruuid = up.useruuid "
				+ " and ud.busuuid = bs.busuuid and dfl.upprouuid = ud.upprouuid and dfl.status = 1 and up.provinceuuid = dfl.provinceuuid "
				+ dfl + ") as 'waitorder',"
				+ " pr.provincename , (select  sum(sum) from (select sum(df.discount_amount) - sum(ups.discount_amount) as 'sum',"
				+ " ups.useruuid,ups.provinceuuid  from uporder ups,businesstype bs,upshopproduct ud,downrechargeflow df where ups.downorderuuid = df.downorderuuid "
				+ " and ud.busuuid = bs.busuuid and ups.upprouuid = ud.upprouuid and ups.status = 2 and df.status = 2 "
				+ profit + ""
				+ " GROUP BY ups.operatoruid,ups.useruuid,ups.provinceuuid) temp where useruuid = up.useruuid and up.provinceuuid = provinceuuid) as 'profit' from uporder up,user u ,"
				+ " businesstype bs,upshopproduct ud ,operators op,provincialinformation pr where u.useruuid = up.useruuid and ud.busuuid = bs.busuuid and "
				+ " up.upprouuid = ud.upprouuid and op.operatoruid = up.operatoruid and pr.provinceuuid = up.provinceuuid  ";

		if (parameters.containsKey("useruuid")) {
			sql += " and up.useruuid ='" + parameters.get("useruuid").toString().concat("' ");
		}
		if (parameters.containsKey("busuuid")) {
			sql += " and bs.busuuid ='" + parameters.get("busuuid").toString().concat("' ");
		}
		if (parameters.containsKey("provinceuuid")) {
			sql += " and pr.provinceuuid  ='" + parameters.get("provinceuuid").toString().concat("' ");
		}
		if (parameters.containsKey("facevalue")) {
			sql += " and up.rechargeamount =" + parameters.get("facevalue").toString().concat(" ");
		}
		if (parameters.containsKey("starttime")) {
			sql += " and DATE_FORMAT(up.createtime,'%Y-%m-%d') >='"
					+ parameters.get("starttime").toString().concat("' ");
		}
		if (parameters.containsKey("endtime")) {
			sql += " and DATE_FORMAT(up.createtime,'%Y-%m-%d') <='" + parameters.get("endtime").toString().concat("' ");
		}
		sql += " GROUP BY   up.useruuid,bs.buscode,up.operatoruid ,bs.busname,pr.provincename";
		return sql;
	}

	// u.upOrderId = ? and
	@Override
	public UpOrder findByWeiLiuTaskId(String taskId, String upOrderUuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.uporderuuid =?",
				upOrderUuid);
	}

	@Override
	public JSONArray exportDataUp(Map<String, Object> parameters) {
		// Page page = PaginationUtil.queryPaginationSQL("select * from
		// ("+sql+") temps", null, this.getSession());
		List lists = this.getSession().createSQLQuery(getSql(parameters)).list();
		if (lists != null) {
			JSONArray array = JsonUtils.getJSONARRAY();
			// [402880ec60e5bd8d0160e5d0f2210001, 111, 全国半年包, 中国电信, 165.0000000,
			// null, null, 165.0000000, 15, 0, 0, 0]
			for (int i = 0; i < lists.size(); i++) {
				JSONObject obj = JsonUtils.getJSONOBJCT();
				Object[] object = (Object[]) lists.get(i);
				obj.put("useruuid", object[0] == null ? "" : object[0].toString());
				obj.put("username", object[1] == null ? "" : object[1].toString());
				obj.put("busname", object[2].toString());
				obj.put("operatorname", object[3].toString());
				// obj.put("sumamount", object[4] == null ? 0 :
				// object[4].toString());
				// obj.put("success", object[5] == null ? 0 :
				// object[5].toString());
				// obj.put("failt", object[6] == null ? 0 :
				// object[6].toString());
				// obj.put("wait", object[7] == null ? 0 :
				// object[7].toString());
				obj.put("sumamount", object[4] == null ? 0 : new BigDecimal(object[4].toString()).setScale(5));
				obj.put("success", object[5] == null ? 0 : new BigDecimal(object[5].toString()).setScale(5));
				obj.put("failt", object[6] == null ? 0 : new BigDecimal(object[6].toString()).setScale(5));
				obj.put("wait", object[7] == null ? 0 : new BigDecimal(object[7].toString()).setScale(5));
				obj.put("sumorder", object[8] == null ? 0 : object[8].toString());
				obj.put("successorder", object[9] == null ? 0 : object[9].toString());
				obj.put("failtorder", object[10] == null ? 0 : object[10].toString());
				obj.put("waitorder", object[11] == null ? 0 : object[11].toString());
				obj.put("provincename", object[12] == null ? 0 : object[12].toString());
				obj.put("profit", object[13] == null ? 0 : new BigDecimal(object[13].toString()).setScale(5));
				obj.put("successRate",
						object[9] == null ? 0
								: (Double.valueOf(object[9].toString())
										/ (object[8] == null ? 0 : Double.valueOf(object[8].toString()))));
				array.add(obj);
			}
			return array;
		}
		return JsonUtils.getJSONARRAY();
	}

	@Override
	public UpOrder findOrderProduct(String uporderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.upShopPro up left join fetch up.businessType where  u.uporderuuid = ? ",
				uporderuuid);
	}

	@Override
	public UpOrder updateOrderMatch(UpOrder order) {
		// TODO Auto-generated method stub
		if (order != null) {
			this.updateEntity(order);
			// 更新自动订单匹配 状态
			return order;
		}
		return null;
	}

	@Override
	public List findDiscount() {
		String sql = "SELECT u.uporderuuid FROM uporder u where u.discount_amount is null";
		return this.getSession().createSQLQuery(sql).list();
	}

	@Override
	public UpOrder findByIdFail(String orderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.upShopPro where u.uporderuuid = ? and  ( u.status = 1 or u.status = 10 or u.status = 11 or u.status = 2 or u.status = 5 ) ",
				orderuuid);
	}

	@Override
	public UpOrder findByIdFailUpOrder(String downorderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder where  u.downRechargeFlow.downorderuuid = ? and  ( u.status = 1 or u.status = 10 or u.status = 11 or u.status = 2 or u.status = 5 ) ",
				downorderuuid);

	}

	@Override
	public UpOrder findByIdSuccess(String orderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder where  u.uporderuuid = ? and  ( u.status = 1 or u.status = 10 or u.status = 11 ) ",
				orderuuid);
	}

	@Override
	public UpOrder findByIdWait(String uporderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder where  u.uporderuuid = ? and u.status = 5 ",
				uporderuuid);
	}

	@Override
	public UpOrder findByIdNormal(String orderuuid) {
		return this.findUnique("select u from UpOrder u left join fetch u.userOrder where u.uporderuuid = ? ",
				orderuuid);
	}

	@Override
	public UpOrder findByheifeixinOrderId(String childOrder) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.childOrder = ? ",
				childOrder);
	}

	@Override
	public List<UpOrder> exportdataUpOrder(Map<String, Object> parameter) {
		return this.findByNamed(getPageSql(parameter,true), parameter);
	}

//	@Override
//	public List findBackAmount() {
//		String sql = "SELECT  up.uporderuuid FROM uporder up where up.useruuid = '0000000060f060350160ff9425bc0016' and up.status = 2 and up.rechargeamount != (select df.rechargeamount from downrechargeflow df where df.downorderuuid = up.downorderuuid)";
//		return this.getSession().createSQLQuery(sql).list();
//	}

	@Override
	public UpOrder findBackAmountOrderId(String uporderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.upShopPro left join fetch u.downRechargeFlow f left join fetch f.downShopProduct where u.uporderuuid  = ? ",
				uporderuuid);
	}

	@Override
	public JSONArray countProfit(Map<String, Object> parameter, int start, int pageSize) {
		// "starttime","endtime","useruuid","provinceuuid","busuuid","facevalue"
		// select sum(df.rechargeamount * df.discount ) - ( select
		// sum(up.rechargeamount * up.discount) from uporder up
		// where up.`status` = 2) from downrechargeflow df where df.status = 2;
		String sql = "select sum(df.discount_amount ) - ( select sum(up.discount_amount) from uporder up where up.status = 2 ";

		if(parameter.containsKey(":useruuid")){
			sql += " and up.useruuid = '"+parameter.get(":useruuid").toString()+"'";
		}

		if (parameter.containsKey(":starttime")) {
			sql += " and up.createtime >='" + parameter.get(":starttime").toString().concat(" 00:00:00' ");
		}

		if (parameter.containsKey(":endtime")) {
			sql += " and  up.createtime <='" + parameter.get(":endtime").toString().concat(" 23:59:59' ");
		}
		sql += ") as profit from down_order df where df.status = 2 ";

		if (parameter.containsKey(":starttime")) {
			sql += " and  df.createtime >='" + parameter.get(":starttime").toString().concat(" 00:00:00' ");
		}

		if (parameter.containsKey(":endtime")) {
			sql += " and df.createtime  <='" + parameter.get(":endtime").toString().concat(" 23:59:59' ");
		}

		if(parameter.containsKey(":useruuid")){
			sql += " and df.downorderuuid in ( select u.downorderuuid from uporder u where u.useruuid = '"+parameter.get(":useruuid").toString()+"' and u.status = 2 " ;
			if (parameter.containsKey(":starttime")) {
				sql += " and u.createtime >='"+parameter.get(":starttime").toString().concat(" 00:00:00' ");
			}

			if (parameter.containsKey(":endtime")) {
				sql += " and  u.createtime <='"+ parameter.get(":endtime").toString().concat(" 23:59:59' ");
			}
			sql += " )";

		}

		Page page = new Page();
		page.setStart(start);
		page.setPageSize(pageSize);
		JSONArray arrays = JsonUtils.getJSONARRAY();
		List lists = PaginationUtil.queryPaginationNotCountSQL(sql, page, this.getSession()).getResult();
		if (lists != null && !lists.isEmpty()) {
			for (int i = 0; i < lists.size(); i++) {
				JSONObject obj = JsonUtils.getJSONOBJCT();
				// Object [] objs = (Object[]) ;
				obj.put("profit", lists.get(i) == null ? "0" : new BigDecimal(lists.get(i).toString()).setScale(5));
				arrays.add(obj);
			}
		}
		return arrays;
	}

	@Override
	public String countDownProfit(Map<String, Object> parameters, int start, int pageSize) {
		Page pa = new Page();
		pa.setStart(start);
		pa.setPageSize(pageSize);
		Page page = PaginationUtil.queryPaginationSQL("select * from (" + getcountDownProfit(parameters) + ") temps ", pa,
				this.getSession());
		List lists = page.getResult();
		if (lists != null && !lists.isEmpty()) {
			JSONArray array = JsonUtils.getJSONARRAY();
			for (int i = 0; i < lists.size(); i++) {
				JSONObject obj = JsonUtils.getJSONOBJCT();
				Object[] object = (Object[]) lists.get(i);
				obj.put("downfacevalue", object[0] == null ? "" : object[0].toString());
				obj.put("discountDown", object[1] == null ? "" : object[1].toString());

				obj.put("upname", object[2].toString());
				obj.put("discountUp", object[3] == null ? 0 :object[3].toString());
				obj.put("username", object[4] == null ? 0 : object[4].toString());

				obj.put("profit", object[5] == null ? 0 : object[5].toString());
				array.add(obj);
			}
			page.setResult(array);
			return JsonUtils.convertObjectToJson(page);
		}
		return JsonUtils.getJSONARRAY().toString();
	}

	private String getcountDownProfit(Map<String, Object> parameters) {
		String sql = "  SELECT sum(d.discount_amount),sum(d.rechargeamount),sum(u.discount_amount),sum(u.rechargeamount),ur.username,sum(d.discount_amount) - sum(u.discount_amount) " +
				" from down_order d " +
				" inner join uporder u on u.downorderuuid = d.downorderuuid and u.`status` = 2" +
				" inner join user ur on ur.useruuid = d.useruuid" +
				" where d.`status` = 2  " ;
		// 总订单数
		if (parameters.containsKey(":useruuid") && !StringUtils.isBlank(parameters.get(":useruuid").toString())) {
			sql += " and d.useruuid = '" + parameters.get(":useruuid") + "'";
		}
		if (parameters.containsKey(":downprouuid") && !StringUtils.isBlank(parameters.get(":downprouuid").toString())) {
			sql += " and d.downprouuid = '' '" + parameters.get(":downprouuid") + "'";
		}
		if (parameters.containsKey(":busuuid") && !StringUtils.isBlank(parameters.get(":busuuid").toString())) {
			sql += "and bt.busuuid = '" + parameters.get(":busuuid") + "'";
		}
		if (parameters.containsKey(":starttime") && !StringUtils.isBlank(parameters.get(":starttime").toString())) {
			sql += "  and  d.createtime >= '" + parameters.get(":starttime").toString() + "'";
		}
		if (parameters.containsKey(":endtime") && !StringUtils.isBlank(parameters.get(":endtime").toString())) {
			sql += " and d.createtime <= '" + parameters.get(":endtime").toString() + "'";
		}

		sql += "  GROUP BY d.useruuid,u.useruuid  ";
		return sql;
	}

	@Override
		public String countProfitRate(Map<String, Object> parameters, int start, int pageSize) {
			Page pa = new Page();
			pa.setStart(start);
			pa.setPageSize(pageSize);
			Page page = PaginationUtil.queryPaginationSQL("select * from (" + getCountProfitRateSql(parameters) + ") temps ", pa,
					this.getSession());
			List lists = page.getResult();
			if (lists != null && !lists.isEmpty()) {
				JSONArray array = JsonUtils.getJSONARRAY();
				for (int i = 0; i < lists.size(); i++) {
					JSONObject obj = JsonUtils.getJSONOBJCT();
					Object[] object = (Object[]) lists.get(i);
					obj.put("num", object[0] == null ? "" : object[0].toString());
					obj.put("price", object[1] == null ? "" : object[1].toString());

					obj.put("cb", object[2].toString());
					obj.put("profit", object[3] == null ? 0 :object[3].toString());
					obj.put("rate", object[4] == null ? 0 : object[4].toString());

					obj.put("name", object[5] == null ? 0 : object[5].toString());
					obj.put("product", object[6] == null ? 0 :object[6].toString());
					obj.put("bustype", object[7] == null ? 0 :object[7].toString());
					array.add(obj);
				}
				page.setResult(array);
				return JsonUtils.convertObjectToJson(page);
			}
			return JsonUtils.getJSONARRAY().toString();
	}

	private String getCountProfitRateSql(Map<String, Object> parameters) {
		String sql = " SELECT count(*) '充值笔数',round(sum(d.discount_amount),2) '售价',round(sum(u.discount_amount),2)'成本', round(sum(d.discount_amount) - sum(u.discount_amount),2) as '利润'," +
				" round(((sum(d.discount_amount) - sum(u.discount_amount))/ sum(u.discount_amount) * 100 ),2)" +
				" '利润率',us.username '分销名称',dp.product_name '产品',bt.busname '业务类型' " +
				" from uporder u" +
				" left JOIN down_order d on d.downorderuuid = u.downorderuuid and d.`status` = 2" +
				" left join user us on us.useruuid = d.useruuid" +
				" left join downshopproduct dp on dp.downprouuid = d.downprouuid" +
				" left join businesstype bt on bt.busuuid = dp.busuuid" +
				" where u.`status` = 2 ";

		// 总订单数
		if (parameters.containsKey(":useruuid") && !StringUtils.isBlank(parameters.get(":useruuid").toString())) {
			sql += "and u.useruuid ='" + parameters.get(":useruuid") + "'";
		}
		if (parameters.containsKey(":operatoruid") && !StringUtils.isBlank(parameters.get(":operatoruid").toString())) {
			sql += "and u.operatoruid = '" + parameters.get(":operatoruid") + "'";
		}
		if (parameters.containsKey(":busuuid") && !StringUtils.isBlank(parameters.get(":busuuid").toString())) {
			sql += "and bt.busuuid = '" + parameters.get(":busuuid") + "'";
		}
		if (parameters.containsKey(":starttime") && !StringUtils.isBlank(parameters.get(":starttime").toString())) {
			sql += "and u.createtime >= '" + parameters.get(":starttime").toString() + "'";
		}
		if (parameters.containsKey(":endtime") && !StringUtils.isBlank(parameters.get(":endtime").toString())) {
			sql += "and u.createtime <= '" + parameters.get(":endtime").toString() + "'";
		}

		sql += " GROUP By us.username,dp.product_name,bt.busname order by bt.busname ";
		return sql;
	}

	@Override
	public UpOrder findByEleId(String uporderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.uporderuuid = ? ",
				uporderuuid);
	}

	@Override
	public UpOrder findLeXiang(String serial_number) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.uporderuuid = ? ",
				serial_number);
	}

	@Override
	public UpOrder findByFlowChildOrder(String childOrder) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.childOrder = ? ",
				childOrder);
	}

	/**
	 * 查询充值中的订单 和飞信
	 */
	@Override
	public List<UpOrder> findHeFeixinProduct(String products) {
		String[] temps = products.split(",");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < temps.length; i++) {
			sb.append("\'");
			sb.append(temps[i]);
			sb.append("\'");
			sb.append(",");
		}
		String temp = sb.toString().substring(0, sb.toString().lastIndexOf(","));
		String hql = "select u from UpOrder u left join fetch u.upShopPro where u.status = 1 and u.upShopPro.upprouuid in ("
				+ temp + ") order by u.createtime";
		return this
				.findPageDataByNamed(hql, MapUtil.getMap(), 0, Integer.valueOf(CookieRedis.get("productsHeFeiXinPage")))
				.getList();
	}

	@Override
	public UpOrder findByUpOrderId(String upOrderId) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.downRechargeFlow where u.status = 1 and u.upOrderId = ? ",
				upOrderId);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public String findUpFlowCount(JSONObject json, int start, int pageSize) {
		Page pa = new Page();
		pa.setStart(start);
		pa.setPageSize(pageSize);
		Page page = PaginationUtil.queryPaginationSQL( "select * from ("+ getUpCountFlowSql(json) +") dfs" , pa,
				this.getSession());
		List lists = page.getResult();
		if (lists != null && !lists.isEmpty()) {
			JSONArray array = JsonUtils.getJSONARRAY();
			for (int i = 0; i < lists.size(); i++) {
				JSONObject obj = JsonUtils.getJSONOBJCT();
				Object[] object = (Object[]) lists.get(i);
				obj.put("username", object[0] == null ? "" : object[0].toString());
				obj.put("proname", object[1] == null ? "" : object[1].toString());

//				obj.put("sumcount", object[2].toString());
//				obj.put("summoney", object[3] == null ? 0 : new BigDecimal(object[3].toString()).setScale(5));
//				obj.put("sumdis", object[4] == null ? 0 : new BigDecimal(object[4].toString()).setScale(5));

				obj.put("sumcount", ( object[2] == null ? 0 : Integer.valueOf(object[2].toString()) + (object[5] == null ? 0 : Integer.valueOf(object[5].toString()))));
				obj.put("summoney", BigDecimalUtil.add((object[3] == null ? BigDecimal.ZERO : new BigDecimal(object[3].toString()).setScale(5)),object[6] == null ? BigDecimal.ZERO : new BigDecimal(object[6].toString()).setScale(5)));
				obj.put("sumdis", BigDecimalUtil.add(object[4] == null ? BigDecimal.ZERO : new BigDecimal(object[4].toString()).setScale(5),object[7] == null ? BigDecimal.ZERO : new BigDecimal(object[7].toString()).setScale(5)));

				obj.put("successnum", object[2] == null ? 0 : object[2].toString());
				obj.put("sucmoney", object[3] == null ? 0 : new BigDecimal(object[3].toString()).setScale(5));
				obj.put("sudis", object[4] == null ? 0 : new BigDecimal(object[4].toString()).setScale(5));

				obj.put("failtnum", object[5] == null ? 0 : object[5].toString());
				obj.put("famoney", object[6] == null ? 0 : new BigDecimal(object[6].toString()).setScale(5));
				obj.put("failtdis", object[7] == null ? 0 : new BigDecimal(object[7].toString()).setScale(5));

				// obj.put("count", object[2].toString());
				// obj.put("success", object[3].toString());
				// obj.put("failt", object[4] == null ? 0 : new
				// BigDecimal(object[4].toString()).setScale(5));
				// obj.put("sumamount", object[5] == null ? 0 : new
				// BigDecimal(object[5].toString()).setScale(5));
				// obj.put("sm", object[6] == null ? 0 : new
				// BigDecimal(object[6].toString()).setScale(5));
				// obj.put("fm", object[7] == null ? 0 : new
				// BigDecimal(object[7].toString()).setScale(5));
				// obj.put("profit", 0);
				// obj.put("rechargeamount", object[8] == null ? 0 : new
				// BigDecimal(object[8].toString()).setScale(5));
				array.add(obj);
			}
			page.setResult(array);
			return JsonUtils.convertObjectToJson(page);
		}
		return JsonUtils.getJSONARRAY().toString();
	}

	@Override
	public JSONArray exportDataUpFlow(JSONObject json) {
		List lists = this.getSession().createSQLQuery(getUpCountFlowSql(json)).list();
		if (lists != null && !lists.isEmpty()) {
			JSONArray array = JsonUtils.getJSONARRAY();
			for (int i = 0; i < lists.size(); i++) {
				JSONObject obj = JsonUtils.getJSONOBJCT();
				Object[] object = (Object[]) lists.get(i);
				obj.put("username", object[0] == null ? "" : object[0].toString());
				obj.put("proname", object[1] == null ? "" : object[1].toString());

//				obj.put("sumcount", object[2].toString());
//				obj.put("summoney", object[3] == null ? 0 : new BigDecimal(object[3].toString()).setScale(5));
//				obj.put("sumdis", object[4] == null ? 0 : new BigDecimal(object[4].toString()).setScale(5));

				obj.put("sumcount", ( object[2] == null ? 0 : Integer.valueOf(object[2].toString()) + (object[5] == null ? 0 : Integer.valueOf(object[5].toString()))));
				obj.put("summoney", BigDecimalUtil.add((object[3] == null ? BigDecimal.ZERO : new BigDecimal(object[3].toString()).setScale(5)),object[6] == null ? BigDecimal.ZERO : new BigDecimal(object[6].toString()).setScale(5)));
				obj.put("sumdis", BigDecimalUtil.add(object[4] == null ? BigDecimal.ZERO : new BigDecimal(object[4].toString()).setScale(5),object[7] == null ? BigDecimal.ZERO : new BigDecimal(object[7].toString()).setScale(5)));

				obj.put("successnum", object[2] == null ? 0 : object[2].toString());
				obj.put("sucmoney", object[3] == null ? 0 : new BigDecimal(object[3].toString()).setScale(5));
				obj.put("sudis", object[4] == null ? 0 : new BigDecimal(object[4].toString()).setScale(5));

				obj.put("failtnum", object[5] == null ? 0 : object[5].toString());
				obj.put("famoney", object[6] == null ? 0 : new BigDecimal(object[6].toString()).setScale(5));
				obj.put("failtdis", object[7] == null ? 0 : new BigDecimal(object[7].toString()).setScale(5));
				array.add(obj);
			}
			return array;
		}
		return JsonUtils.getJSONARRAY();
	}

	private String getUpCountFlowSql(JSONObject json) {
		//,sum(counts),sum(sumprice),sum(summoney) ,count(up.uporderuuid) as 'counts', sum(up.rechargeamount) as 'sumprice',sum(up.discount_amount) as 'summoney',
		String sql = " select username,name ,sum(success),sum(price),sum(successmoney),sum(failt),sum(failtprice),sum(failtmoney) from ("
				+ " select (SELECT u.username from user u where u.useruuid = up.useruuid ) as 'username',(select pr.product_name from upshopproduct pr where "
				+ " pr.upprouuid = up.upprouuid) as 'name' ,"
				+ " case up.`status`  when 2 then count(up.upprouuid) end as 'success', case up.`status` when 2 then sum(up.rechargeamount) end  as 'price', "
				+ " case up.`status` when 2 then sum(up.discount_amount) end as 'successmoney', case up.`status` when 3 then count(up.uporderuuid) end as 'failt', "
				+ " case up.`status`  when 3 then sum(up.rechargeamount) end  as 'failtprice', case up.`status` when 3 then sum(up.discount_amount) end  as 'failtmoney' "
				+ " from uporder up  where  (up.`status` = 2 or up.`status` = 3)   ";

		// 总订单数
		if (json.containsKey("useruuid") && !StringUtils.isBlank(json.getString("useruuid"))) {
			sql += "and up.useruuid = '" + json.getString("useruuid") + "'";
		}
		if (json.containsKey("upprouuid") && !StringUtils.isBlank(json.getString("upprouuid"))) {
			sql += "and up.upprouuid = '" + json.getString("upprouuid") + "'";
		}
		if(json.containsKey("provinceuuid") && !StringUtils.isBlank(json.getString("provinceuuid"))){
			sql += "and up.province = '"+json.getString("provinceuuid")+"'";
		}
		if (json.containsKey("starttime") && !StringUtils.isBlank(json.getString("starttime"))) {
			sql += "and up.createtime >= '" + json.getString("starttime") + "'";
		}
		if (json.containsKey("endtime") && !StringUtils.isBlank(json.getString("endtime"))) {
			sql += "and up.createtime <= '" + json.getString("endtime") + "'";
		}

		if (json.containsKey("operatoruid") && !StringUtils.isBlank(json.getString("operatoruid"))) {
			sql += "and up.operatoruid = '" + json.getString("operatoruid") + "'";
		}
		if (json.containsKey("provinceuuid") && !StringUtils.isBlank(json.getString("provinceuuid"))) {
			sql += "and up.province = '" + json.getString("provinceuuid") + "'";
		}

		sql += " GROUP BY up.upprouuid,up.`status`) temps GROUP BY name,username ";
		return sql;
	}

	@Override
	public void updateUpOrder(UpOrder order, String upOrderId) {
		order = this.findById(order.getUporderuuid());
		if (order != null) {
			order.setUpOrderId(upOrderId);
			order.setSendStatus(Config.sendStatus[0]);
			order.setCallBack(Config.callStatus[0]);
			this.updateOrder(order);
		}
	}

	@Override
	public void updateUpOrderMsg(UpOrder order, String upOrderId, String msg) {
		order = this.findById(order.getUporderuuid());
		if (order != null) {
			order.setUpOrderId(upOrderId);
			order.setSendStatus(Config.sendStatus[0]);
			order.setCallBack(Config.callStatus[0]);
			order.setRemark(order.getRemark() == null ? msg : order.getRemark().length() < 100 ? order.getRemark().concat(msg) : msg);
			this.updateOrder(order);
		}
	}

	@Override
	public void updateUpOrderArtificial(UpOrder order, String upOrderId, String msg) {
		order = this.findById(order.getUporderuuid());
		if (order != null) {
			order.setUpOrderId(upOrderId);
			order.setStatus(Config.status[11]);
			order.setRemark(order.getRemark() == null ? msg : order.getRemark().concat(msg));
			this.updateOrder(order);
		}
	}

	@Override
	public void addOrderMsg(UpOrder order, String msg) {
		if(order != null){
			order = this.findByCallId(order.getUporderuuid());
			order.setRemark(msg);
			this.updateOrder(order);
		}
	}

	/**
	 * 提交失败
	 *
	 * @param order
	 * @param
	 */
	@Override
	public void commitFailt(UpOrder order, String msg) {
		if (order != null) {
			order = this.findById(order.getUporderuuid());
			if (order != null) {
				order.setRemark(order.getRemark() == null ? msg : order.getRemark().length() < 100 ? order.getRemark().concat(msg) : msg);
				order.setSendStatus(Config.sendStatus[1]);
				this.updateOrderMatch(order);
			}
		} else {
			Log.info("commitFailt订单为null:" + order);
		}
	}

	/**
	 * 批量转单
	 * @param newProduct
	 * @param upOrder
	 * @param upShopInfo
	 * @return
	 */
	@Override
	public UpOrder batchCommitOrder(UpShopProduct newProduct,UpOrder upOrder,UpShopInfo upShopInfo) {
		//当前渠道订单失败。创建新订单
		upOrder.setStatus(Config.status[2]);
		upOrder.setRemark("已转单,当前订单失败");
		this.updateEntity(upOrder);
		UpOrder newOrder = new UpOrder();
		BeanUtils.copyProperties(upOrder,newOrder);
		newOrder.setUporderuuid(null);
		//检查新选的供货商是否压单 不修改订单状态
//		if(upShopInfo.getPressOrder()){
//			newOrder.setStatus(Config.status[10]);
//		}else{
//			//检查产品是否压单
//			if(newProduct.getPressOrder()){
//				newOrder.setStatus(Config.status[10]);
//			}else{
//				newOrder.setStatus(Config.status[0]);
//			}
//		}

		newOrder.setStatus(Config.status[10]);
		newOrder.setCallBack(Config.callStatus[0]);
		newOrder.setSendStatus(Config.sendStatus[1]);
		newOrder.setRemark("人工转单订单");
		newOrder.setDiscountAmount(newProduct.getPrice().multiply(newProduct.getDiscount()));
		newOrder.setDiscount(newProduct.getDiscount());
		newOrder.setDownRechargeFlow(upOrder.getDownRechargeFlow());
		newOrder.setUpShopPro(newProduct);
		newOrder.setUserOrder(new User(upShopInfo.getUser().getUseruuid()));
		newOrder.setInformation(newProduct.getProvincialInformation());
		newOrder.setUpOrderLogs(null);
		newOrder.setUpOrderRefunds(null);
		newOrder.setUpOrderId("");
		newOrder.setChildOrder("");
		newOrder.setOperatorname(upOrder.getOperatorname());
		//默认是重复提单
		newOrder.setStatusremark(Config.orderStatus[1]);
		newOrder = this.saveOrUpdate(newOrder);
		return newOrder;

	}

	@Override
	public UpOrder findByPressOrder(String uporderuuid) {
		return this.findUnique(
				"select u from UpOrder u left join fetch u.userOrder left join fetch u.upShopPro p  where (u.status = 10 or u.status = 11) and u.uporderuuid = ? ",
				uporderuuid);
	}


	@Override
	public String findByFlowOrder(DownRechargeFlow flow) {
		return this.getSession().createSQLQuery(" SELECT GROUP_CONCAT(u.upprouuid) from uporder u where u.downorderuuid = '"+flow.getDownorderuuid()+"' ").uniqueResult().toString();
	}

	@Override
	public int upCount(String downorderuuid) {
		return Integer.valueOf(this.getSession().createSQLQuery(" SELECT count(u.upprouuid) from uporder u where u.downorderuuid = '"+downorderuuid+"'").uniqueResult().toString());
	}

	@Override
	public int findbyProduct(String upprouuid) {
		return BigDecimal.valueOf(this.findLong("SELECT count(*) from UpOrder d  where d.upShopPro.upprouuid = ?",upprouuid)).intValue();
	}

	@Override
	public synchronized List<UpOrder> savePageOrderQh(Map<String, Object> parameters, int start, int pageSize, boolean b) {
		synchronized(this){
			Page<UpOrder> orderPage = this.findPageByNamed(getPageSql(parameters,false), parameters, start, pageSize);
			if(CollectionUtils.isEmpty(orderPage.getResult())){
				return new ArrayList<>();
			}
			String upprouuids = "";
			for(int i = 0 ; i < orderPage.getResult().size() ; i++){
				upprouuids += "'"+orderPage.getResult().get(i).getUporderuuid().toString()+"',";
			}
			if(!upprouuids.equals("")){
				upprouuids = upprouuids.substring(0,upprouuids.lastIndexOf(","));
			}
			if(!upprouuids.equals("")){
				List<UpOrder> list = orderPage.getResult();
				for(UpOrder order : list){
					order.setStatus(1);
					this.updateEntity(order);
				}
				return orderPage.getResult();
			}

			return new ArrayList<>();
		}
	}
}
